package Top_Interview_Questions_Review._008Two_Pointers;

/**
 * @Author: 吕庆龙
 * @Date: 2020/3/8 20:29
 * <p>
 * 功能描述:
 */
public class _0202 {

    public static void main(String[] args) {
        _0202 test = new _0202();
        test.isHappy(19);
    }

    /**
     * https://leetcode-cn.com/problems/happy-number/solution/shi-yong-kuai-man-zhi-zhen-si-xiang-zhao-chu-xun-h/
     *
     * #.有一点没弄明白,是怎么知道一定有环的呢？
     * #.底下的评论:
     * 尝试着输入特别大的数字去测试，最后发现并没有超时，而且输入的所有数字到最后都会产生循环，
     * 只不过不一定是1。很神奇！
     */
    public boolean isHappy(int n) {
        int slow = n, fast = n;
        do{
            slow = bitSquareSum(slow);
            fast = bitSquareSum(fast);
            fast = bitSquareSum(fast);
        }while(slow != fast);

        return slow == 1;
    }

    public int bitSquareSum(int n) {
        int sum = 0;
        while(n > 0)
        {
            int bit = n % 10;
            sum += bit * bit;
            n = n / 10;
        }
        return sum;
    }

}
